package com.szewec.ps.util.fir;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.View;

import com.szewec.ps.MainActivity;
import com.szewec.ps.base.CommonDialog;
import com.szewec.ps.util.GsonUtil;
import com.szewec.ps.util.LogUtil;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.SharedPreferencesUtil;
import com.szewec.ps.util.okhttp.OkHttp;

public class AppVersionUpdate {

    private static String TAG = "AppVersionUpdate";
    private static CommonDialog commonDialog;

    /**
     * 获取版本号
     *
     * @throws PackageManager.NameNotFoundException
     */
    public static String getVersionName(Context context) throws PackageManager.NameNotFoundException {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        String version = packInfo.versionName;
        LogUtil.i("当前版本", version);
        return version;
    }

    /**
     * 版本号比较
     * 0代表相等，1代表version1大于version2，-1代表version1小于version2
     *
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    //    /**
//     * 从服务器获取版本最新的版本信息
//     */
    public static void getVersionInfoFromServer(Context context, String url) {
        //模拟从服务器获取信息  模拟更新王者荣耀
        OkHttp.getWithoutBaseUrl(url, new OkHttp.MyCallback() {
            @Override
            public void onSuccess(String result) {
                LogUtil.i(TAG, "fir更新信息:" + result);
                VersionInfoBean versionInfoBean = GsonUtil.GsonToBean(result, VersionInfoBean.class);
                SharedPreferencesUtil.putData(PreferincesContext.APKURL, versionInfoBean.getInstallUrl());
                //比较版本信息
                try {
                    LogUtil.i("服务器最新版本:", versionInfoBean.getVersionShort());
                    int isNewest = compareVersion(getVersionName(context), versionInfoBean.getVersionShort());
                    if (isNewest == -1) {
                        //不是最新版本
                        //兼容8.0
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                            if (!hasInstallPermission) {
                                showUnKnowAppDialog(context);
                            } else {
                                boolean isLoading = (boolean) SharedPreferencesUtil.getData(PreferincesContext.APKDOWNLOADSTATE, false);
                                if (isLoading) {
                                    LogUtil.i(TAG, "apk任务下载中");
                                } else {
                                    showDialog(context, versionInfoBean);
                                }
                            }
                        } else {
                            boolean isLoading = (boolean) SharedPreferencesUtil.getData(PreferincesContext.APKDOWNLOADSTATE, false);
                            if (isLoading) {
                                LogUtil.i(TAG, "apk任务下载中");
                            } else {
                                showDialog(context, versionInfoBean);
                            }
                        }
                    } else {
                        MainActivity.appVersionInterface.newestVersion();
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    private static void showUnKnowAppDialog(Context context) {
        final CommonDialog commonDialog = new CommonDialog(context);
        commonDialog.setContentMargin();//设置左右间距
        commonDialog.setTitle("未知来源");
        commonDialog.setContent("为保证安装任意渠道应用的安全性,请您先开启允许安装未知来源!");
        commonDialog.setContent2("如要更改此来源的设置,点击【设置】>进入【安装未知应用】,然后选择此来源并启用【允许安装未知应用】。");
        commonDialog.setEnsure("设置");
        commonDialog.setCancelable(false);//设置不可关闭
        commonDialog.setOnEnsureClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 点击“确认”后的操作
                //注意这个是8.0新API
                //跳转到设置-允许安装未知来源-页面
                Intent intentUNKNOWN_APP = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                intentUNKNOWN_APP.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intentUNKNOWN_APP);
                commonDialog.dismiss();
            }
        });
        commonDialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((Activity) context).finish();
                commonDialog.dismiss();
            }
        });
        commonDialog.show();
    }

    private static void showDialog(Context context, VersionInfoBean versionInfoBean) {
        commonDialog = new CommonDialog(context);
        commonDialog.setTitle("更新提示");
        commonDialog.setContent("更新最新版本？");
        commonDialog.setCancelable(false);//设置不可关闭
        commonDialog.setEnsure("立即升级");
        commonDialog.setModelOk();//ok模式
        commonDialog.setOnEnsureClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(versionInfoBean.getInstallUrl()));
                context.startActivity(i);
                commonDialog.dismiss();
            }
        });
        commonDialog.show();//展示
    }

    public static void dismissDialog() {
        if (null != commonDialog) {
            commonDialog.dismiss();
        }
    }
}
